package com.firstgroup.dms.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Object user = request.getSession().getAttribute("yongHu");
		System.out.println("afterCompletion----" + user + " ::: " + request.getRequestURL());
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		Object user = request.getSession().getAttribute("yongHu");
		System.out.println("postHandle----" + user + " ::: " + request.getRequestURL());
	}

	/**
	 * 拦截验证，如果请求中没有用户对象，代表用户没有登录，跳转回到登录页面
	 * 
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Object user = request.getSession().getAttribute("yongHu");
		System.out.println(
				"preHandle----" + user + " ::: " + request.getRequestURL() + "   ----   " + request.getRequestURI());
		System.out.println("======================================session id = " + request.getSession().getId());
		System.out.println("====================================getLocalAddr = " + request.getLocalAddr());
		System.out.println("===================================getRemoteHost = " + request.getRemoteHost());
		System.out.println("===================================getRemoteAddr = " + request.getRemoteAddr());

		if (user == null) {
			request.setAttribute("msg", "无权限请先登录");
			// 修改为重定向到登录页面的正确路径
			response.sendRedirect("/login/login.html");
			return false;
		}
		return true;
	}
}